/*
 * 简介: nodejs TCP服务连接
 * 作者: 洪松
 * 时间: 2023/11/1 15:27
 */
//创建服务器
const net = require('net')
const server = net.createServer()
//连接数据库
var database = require("./database");

//家居服务器tcp连接
var home = null;
//传输来的数据
var cachecontent = "";
//最新数据缓存
var latestData = "";

//软件列表
var softwares = [];

server.on('connection', clientSocket => {
    console.log('接收到连接请求');

    //监听 clientScoket的data 信息
    clientSocket.on('data', (data) => {
        let content = data.toString();
        content = content.replace(/ /g, '').replace(/\n/g, '').replace(/\r/g, '');
        cachecontent += content;
        if (cachecontent.includes("EOF")) {
            cachecontent = cachecontent.replace("EOF", "");
            try {
                const json_data = JSON.parse(cachecontent);
                parse_json(clientSocket, json_data);
            } catch (err) {
                cachecontent = "";
                return;
            }
            cachecontent = "";
        }
    })

    clientSocket.on("error", err => { });

    // 监听客户端断开连接事件
    clientSocket.on('end', () => {
        
    });
})

server.listen(80, () => {
    console.log('服务器已启动');
})

//解析Json
function parse_json(client, data) {
    switch (data.DT) {
        case 0:  //接收来自硬件的请求
            parse_home(client, data);
            break;
        case 1:  //接收来自软件的请求
            parse_software(client, data);
            break;
    }
}

// 解析硬件的请求
function parse_home(client, data) {
    switch (data.Type) {
        case 0:  //绑定请求
            home = client;
            console.log('接收到家居绑定服务器请求');
            client.write('bind successful');
            break;
        case 1: //上传数据
            update_data(data);
            break;
    }
}

//更新数据
function update_data(data) { 
    latestData = '{"DT":2,"Type":3,"Data":' + JSON.stringify(data.Data) + '}';
    //同步更新数据
    softwares.forEach((item) => {
        item.write(latestData);
    });

    const sql = "INSERT INTO equipment (Data, Time) VALUES ('" + JSON.stringify(data.Data) + "', NOW());"
    //数据库长度限制 超过1000条将删除最旧的数据并插入新的数据
    database.query("SELECT COUNT(*) AS row_count FROM equipment;", function (results) { 
        if (results[0].row_count >= 1000) {
            database.query("DELETE FROM homedb.equipment ORDER BY ID ASC LIMIT 1;", function (results) {
                database.query(sql, function (results) { });
            });
        }
        else {
            database.query(sql, function (results) { });
        }
    });
}

//解析软件的请求
function parse_software(client, data) {
    switch (data.Type) {
        case 0:  //绑定请求(无法绑定来自软件的请求)
            console.log('接收到软件绑定服务器请求');
            if (softwares.includes(client)) {
                softwares.pop(client);
                softwares.push(client);
            } else { 
                softwares.push(client);
            }
            get_latestData(client);
            break;
        case 1: //上传数据
            console.log("发送测试数据给家庭硬件");   
            home.write("this message form software"); 
            break;
        case 2: //控制命令
            if (home != null) {
                console.log("发送命令给家庭硬件->"+JSON.stringify(data));
                home.write(JSON.stringify(data));
                softwares.forEach((item) => {
                    item.write(JSON.stringify(data));
                });
            }
            break;
        case 3: //下载最新数据
            get_latestData(client);
            break;
        case 4: //获取全部数据
            database.query("SELECT Data,Time FROM equipment;", function(results){ 
                client.write(JSON.stringify(results));
            });
            break;
        case 5: //状态检查
            client.write(home == null? "Offline" : "online");
            break;
    }
}

//获取最新数据
function get_latestData(client) {
    if (latestData == "") { 
        database.query("SELECT Data FROM equipment ORDER BY ID DESC LIMIT 1;", function (results) { 
            latestData = '{"DT":2,"Type":3,"Data":' + results[0].Data + '}';
            client.write(latestData);
        });
    } else {
        client.write(latestData);
    }
}